package lixp.security.config.handler;

import lixp.pojo.UpmsPermission;
import lixp.security.service.SecurityService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;


/**
 * 匹配请求需要哪些对应的权限（通过URL查询数据库中的权限）
 */
@Component
public class MyFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    Logger logger = LoggerFactory.getLogger(MyFilterInvocationSecurityMetadataSource.class);

    private HashMap<String, Collection<ConfigAttribute>> map = null;


    @Autowired
    SecurityService securityService;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        logger.error("----------->getAttributes");
        String requestUrl = ((FilterInvocation) object).getRequestUrl();

        //查询具体某个接口的权限
        List<UpmsPermission> permissionList =  securityService.selectUpmsPermissionByUrl(requestUrl);
        if(permissionList == null || permissionList.size() == 0){
            //请求路径没有配置权限，表明该请求接口可以任意访问
            return null;
        }
        String[] attributes = new String[permissionList.size()];
        for(int i = 0;i<permissionList.size();i++){
            if (StringUtils.isNotBlank(permissionList.get(i).getPermissionValue())){
                attributes[i] = permissionList.get(i).getPermissionValue();
            }
            else {
                return null;
            }

        }
        return SecurityConfig.createList(attributes);

    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        logger.info("----------->getAllConfigAttributes");
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }


}
